# -- coding: utf-8 --
import sys
import io
from dotenv import load_dotenv
import os
import requests
import json
import time
from typing import List, Dict, Any

# 设置标准输出的编码为UTF-8  day5已设置
# if sys.stdout.encoding != "UTF-8":
#     sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8", errors="replace")

# 添加day5文件夹到Python路径
current_dir = os.path.dirname(os.path.abspath(__file__))
parent_dir = os.path.dirname(current_dir)
day5_dir = os.path.join(parent_dir, "day5")

print(f"调试信息:")
print(f"当前目录: {current_dir}")
print(f"父目录: {parent_dir}")
print(f"Day5目录: {day5_dir}")
if os.path.exists(day5_dir):
    sys.path.insert(0, day5_dir)
    print(f"已添加Day5路径: {day5_dir}")
else:
    print("Day5目录不存在")

load_dotenv()


# 导入day5的模块
try:
    from doc_split_real import (
        create_sample_documents,
        document_splitting_demo,
        real_embedding_vectorization_demo,
        create_advanced_vector_store,
    )

    DAY5_AVAILABLE = True
    print("✅ 成功导入Day5模块")
except ImportError as e:
    print(f"❌ 无法导入Day5模块: {e}")
    DAY5_AVAILABLE = False
    # 这里可以添加备用方案


class DeekSeekClient:
    """DeepSeek API客户端"""

    def __init__(self, api_key: str = None, base_url: str = "https://api.deepseek.com"):
        self.api_key = api_key or os.getenv("DEEPSEEK_API_KEY")
        self.base_url = base_url
        self.headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {self.api_key}",
        }

    def chat_completion(
        self,
        messages: List[Dict],
        model: str = "deepseek-chat",
        temperature: float = 0.7,
        max_tokens: int = 2000,
    ) -> Dict:
        """调用DeepSeek聊天补全API"""

        # 如果没有API密钥，使用模拟响应
        if not self.api_key:
            return self._mock_response(messages)

        payload = {
            "model": model,
            "messages": messages,
            "temperature": temperature,
            "max_tokens": max_tokens,
            "stream": False,
        }

        try:
            response = requests.post(
                f"{self.base_url}/chat/completions",
                headers=self.headers,
                json=payload,
                timeout=30,
            )
            response.raise_for_status()
            return response.json()
        except Exception as e:
            print(f"❌ DeepSeek API调用失败: {e}")
            return self._mock_response(messages)

    def _mock_response(self, mesages: List[Dict]) -> Dict:
        """模拟API响应，用于测试"""
        last_message = mesages[-1]["content"]

        # 简单的规则引擎模拟LLM回答
        mock_responses = {
            "机器学习": "机器学习主要分为监督学习、无监督学习和强化学习三种类型。监督学习使用标记数据训练模型，无监督学习在未标记数据中发现模式，强化学习通过试错学习最优策略。",
            "深度学习": "深度学习是机器学习的一个分支，使用多层神经网络处理复杂模式。它与传统机器学习的区别在于能够自动学习特征表示，无需大量手工特征工程。",
            "神经网络": "神经网络在计算机视觉、自然语言处理、语音识别、推荐系统、医疗诊断、自动驾驶等领域有广泛应用。",
            "RAG": "RAG（检索增强生成）技术通过从外部知识库检索相关信息来增强语言模型的回答，提高准确性和事实性，减少幻觉问题。",
        }

        # 查找最相关的模拟回答
        response_text = "基于检索到的文档内容，我了解到："
        for keyword, answer in mock_responses.items():
            if keyword in last_message:
                response_text += f" {answer}"
                break
            else:
                response_text += " 这是一个关于人工智能技术的问题，涉及机器学习、深度学习等相关概念。"

        return {
            "choices": [{"message": {"content": response_text, "role": "assistant"}}],
            "usage": {
                "total_tokens": 100,
                "prompt_tokens": 50,
                "completion_tokens": 50,
            },
        }


class RAGSystem:
    """完整的RAG系统"""

    def __init__(self, vectorstore, embeddings, deepseek_client):
        self.vectorstore = vectorstore
        self.embeddings = embeddings
        self.deepseek_client = deepseek_client
        self.conversation_history = []

    def _build_prompt(
        self, question: str, context_docs: List, conversation_history: List = None
    ) -> str:
        """构建提示词"""

        # 构建上下文
        context = "\n\n".join([doc.page_content for doc in context_docs])

        # 构建对话历史
        history_text = ""
        if conversation_history:
            for turn in conversation_history[-3:]:  # 只保留最近3轮对话
                history_text += f"用户：{turn['question']}\n助手：{turn['answer']}\n\n"

        prompt = f"""你是一个专业的人工智能助手，基于提供的文档内容回答问题。

相关文档内容：
{context}

对话历史：
{history_text}

当前问题：{question}

请根据以上文档内容回答问题，要求：
1. 回答要准确、详细，基于文档事实
2. 如果文档中没有相关信息，请明确说明
3. 保持专业性和友好性
4. 用中文回答

回答: """
        return prompt

    def ask_question(self, question: str, k: int = 3) -> Dict[str, Any]:
        """提问并获取回答"""

        print(f"\n🔍 正在检索相关信息...")

        # 1. 检索相关文档
        relevant_docs = self.vectorstore.similarity_search(question, k=k)

        if not relevant_docs:
            return {
                "answer": "抱歉，在知识库中没有找到相关信息。",
                "sources": [],
                "retrieved_count": 0,
            }

        print(f"✅ 检索到 {len(relevant_docs)} 个相关文档片段")

        # 2. 构建提示词
        prompt = self._build_prompt(question, relevant_docs, self.conversation_history)

        # 3. 调用DeepSeek生成回答
        messages = [
            {
                "role": "system",
                "content": "你是一个专业的人工智能助手，基于提供的文档内容准确回答问题。",
            },
            {"role": "user", "content": prompt},
        ]

        print("🤖 正在生成回答...")
        response = self.deepseek_client.chat_completion(messages)

        # 4. 提取回答
        answer = response["choices"][0]["message"]["content"]

        # 5. 更新对话历史
        self.conversation_history.append(
            {"question": question, "answer": answer, "timestamp": time.time()}
        )

        # 限制对话历史长度
        if len(self.conversation_history) > 5:
            self.conversation_history = self.conversation_history[-5:]

        return {
            "answer": answer,
            "sources": relevant_docs,
            "retrieved_count": len(relevant_docs),
            "tokens_used": response.get("usage", {}).get("total_tokens", 0),
        }

    def clear_history(self):
        """清空对话历史"""
        self.conversation_history = []
        print("✅ 对话历史已清空")


def setup_rag_system(vectorstore, embeddings):
    """设置RAG系统"""
    print("\n🚀 初始化完整RAG系统")
    print("-" * 40)

    # 初始化DeepSeek客户端
    deepseek_Client = DeekSeekClient()

    # 初始化RAG系统
    rag_system = RAGSystem(vectorstore, embeddings, deepseek_Client)

    print("✅ RAG系统初始化完成!")
    print("   - 向量数据库: 已加载")
    print("   - 嵌入模型: 已就绪")
    print("   - DeepSeek客户端: 已连接")
    print("   - 对话系统: 已启用")

    return rag_system


def interactive_demo(rag_system):
    """交互式演示"""
    print("\n💬 交互式RAG问答系统")
    print("=" * 50)
    print("输入 'quit' 退出系统")
    print("输入 'clear' 清空对话历史")
    print("输入 'history' 查看对话历史")
    print("=" * 50)

    while True:
        try:
            question = input("\n❓ 请输入问题: ").strip()

            if question.lower() == "quit":
                print("👋 感谢使用，再见！")
                break
            elif question.lower() == "clear":
                rag_system.clear_history()
                continue
            elif question.lower() == "history":
                print("\n📜 对话历史:")
                if rag_system.conversation_history:
                    for i, turn in enumerate(rag_system.conversation_history, 1):
                        print(f"  {i}. 用户: {turn['question']}")
                        print(f"     助手: {turn['answer'][:100]}...")
                    continue
                elif not question:
                    continue

            # 回答问题
            start_time = time.time()
            result = rag_system.ask_question(question)
            response_time = time.time() - start_time

            # 显示结果
            print(f"\n💡 回答 (响应时间: {response_time:.2f}s)：")
            print(f"    {result['answer']}")

            print(f"\n📚 参考来源 ({result['retrieved_count']} 个文档片段")
            for i, doc in enumerate(result["sources"], 1):
                source_info = doc.metadata.get("source", "未知来源")
                chunk_id = doc.metadata.get("chunk_id", "未知")
                content_preview = (
                    doc.page_content[:80] + "..."
                    if len(doc.page_content) > 80
                    else doc.page_content
                )

                print(f"   {i}.[{source_info}--{chunk_id}]{content_preview}")

            if result.get("tokens_used"):
                print(f"🔢 令牌使用: {result['tokens_used']} tokens")

        except KeyboardInterrupt:
            print("\n👋 用户中断，再见！")
            break
        except Exception as e:
            print(f"❌ 发生错误: {e}")


def advanced_rag_demo(rag_system):
    """高级RAG功能演示"""
    print("\n🔬 高级RAG功能演示")
    print("-" * 40)

    test_cases = [
        {
            "question": "请详细解释机器学习的主要类型及其应用场景",
            "description": "复杂技术问题",
        },
        {
            "question": "深度学习和传统机器学习有什么区别？各有什么优缺点？",
            "description": "对比分析问题",
        },
        {
            "question": "RAG技术如何解决大语言模型的幻觉问题？",
            "description": "技术原理问题",
        },
        {
            "question": "请总结神经网络在现实世界中的主要应用领域",
            "description": "应用总结问题",
        },
    ]

    for i, case in enumerate(test_cases, 1):
        print(f"\n🧪 测试案例 {i}:{case['description']}")
        print(f"   ❓ 问题: {case['question']}")

        result = rag_system.ask_question(case["question"])

        print(f"   💡 回答: {result['answer'][:150]}...")
        print(f"   📊 检索文档数: {result['retrieved_count']}")

        if result.get("tokens_used"):
            print(f"   🔢 令牌使用: {result['tokens_used']} tokens")

        # 添加延迟避免频繁调用
        time.sleep(1)


def performance_analysis(rag_system):
    """性能分析"""
    print("\n📊 RAG系统性能分析")
    print("-" * 40)

    # 测试问题
    test_questions = [
        "什么是机器学习？",
        "深度学习有哪些应用？",
        "解释一下Transformer架构",
        "RAG技术的优势是什么？",
    ]

    total_time = 0
    total_tokens = 0
    successful_queries = 0

    for question in test_questions:
        try:
            start_time = time.time()
            result = rag_system.ask_question(question, k=2)
            end_time = time.time()

            response_time = end_time - start_time
            total_time += response_time
            total_tokens += result.get("tokens_used", 0)

            successful_queries += 1
            print(f"   ✅ '{question}' - {response_time:.2f}s")
        except Exception as e:
            print(f"   ❌ '{question}' - 错误：{e}")

    if successful_queries > 0:
        avg_time = total_time / successful_queries
        avg_tokens = total_tokens / successful_queries if total_tokens > 0 else 0

        print(f"\n📈 性能统计:")
        print(f"   平均响应时间: {avg_time:.2f}秒")
        print(f"   平均令牌使用: {avg_tokens:.0f} tokens")
        print(f"   成功率: {successful_queries}/{len(test_questions)}")
    else:
        print("❌ 没有成功的查询可供分析")


def main():
    """主函数"""
    print("🎯 Day 6 - 集成DeepSeek完成完整RAG系统")
    print("=" * 60)
    if not DAY5_AVAILABLE:
        print("❌ Day5模块不可用，无法继续")
        print("💡 请确保day5文件夹存在且包含doc_split_real.py文件")
        return
    # 创建或加载已有的文档和向量数据库
    print("📁 加载Day 5的文档和向量数据库...")

    # 确保在正确的目录中创建文档
    original_dir = os.getcwd()
    try:
        # 切换到day5目录（因为文档路径是相对路径）
        os.chdir(day5_dir)

        create_sample_documents()
        split_results = document_splitting_demo()
        embeddings = real_embedding_vectorization_demo()

        if embeddings and split_results:
            vectorstore = create_advanced_vector_store(split_results, embeddings)
        else:
            print("❌ 无法创建向量数据库")
            return
    except Exception as e:
        print(f"❌ 加载Day 5组件时出错: {e}")
        return
    finally:
        # 切换回原始目录
        os.chdir(original_dir)

    #   设置RAG系统
    rag_system = setup_rag_system(vectorstore, embeddings)

    # 性能分析
    performance_analysis(rag_system)

    # 高级演示
    advanced_rag_demo(rag_system)

    # 交互式问答 - 确保这行代码存在且没有被注释
    print("\n" + "=" * 60)
    print("🚀 开始交互式问答演示")
    print("=" * 60)
    interactive_demo(rag_system)  # 确保这行代码存在

    print("\n" + "=" * 60)
    print("🎉 Day 6 学习完成！")

    print("\n📚 今日学习总结:")
    print("   ✅ DeepSeek API集成 - 掌握大语言模型调用")
    print("   ✅ 完整RAG流水线 - 实现检索增强生成系统")
    print("   ✅ 提示工程优化 - 改进回答质量")
    print("   ✅ 交互式界面 - 实现用户友好对话")
    print("   ✅ 性能监控 - 分析系统表现")

    print("\n🔧 核心技术要点:")
    print("   1. DeepSeek API调用 - RESTful接口使用")
    print("   2. RAG系统架构 - 检索+生成的完整流程")
    print("   3. 提示词构建 - 上下文管理和历史维护")
    print("   4. 错误处理 - 网络超时和API限制处理")
    print("   5. 对话管理 - 多轮对话上下文保持")

    print("\n🚀 下一步学习:")
    print("   📍 Day 7: 对话记忆和上下文管理")
    print("   📍 Day 8: 项目部署和性能优化")
    print("   📍 Day 9: 高级RAG技术和多模态扩展")

    print("\n💡 实践建议:")
    print("   1. 申请DeepSeek API密钥体验真实模型")
    print("   2. 尝试不同的提示词模板优化回答质量")
    print("   3. 测试系统在复杂问题上的表现")
    print("   4. 考虑添加缓存机制提高响应速度")


if __name__ == "__main__":
    main()
